package com.weilele.mvvm.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.OverScroller

/**
 * OverScroller 的使用示例
 * 功能暂未完善
 */
open class OverScrollLayout : BaseNestedScrollingParentLayout {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    init {
        isNestedScrollingEnabled = true
    }

    /**
     * ----------scroll---------
     * startX	x轴起点坐标
     * startY	y轴起点坐标
     * dx	x轴滑动距离
     * dy	Y轴滑动距离
     * duration	滑动时间，缺省250ms
     *
     * --------fling-----------
     * velocityX	x轴手指离开时的初始速度
     *  velocityY	y轴手指离开时的初始速度
     *  minX	x轴惯性滑动最短的滑动距离
     *  maxX	x轴惯性滑动最长的滑动距离
     *  minY	y轴惯性滑动最短的滑动距离
     *  maxY	y轴惯性滑动最长的滑动距离
     *  overX   x轴回弹边界
     *  overY   y轴回弹边界
     */
    private val scroller by lazy { OverScroller(context) }

    override fun onNestedScroll(
        target: View,
        dxConsumed: Int,
        dyConsumed: Int,
        dxUnconsumed: Int,
        dyUnconsumed: Int,
        type: Int,
        consumed: IntArray
    ) {
        super.onNestedScroll(
            target,
            dxConsumed,
            dyConsumed,
            dxUnconsumed,
            dyUnconsumed,
            type,
            consumed
        )
    }


    override fun computeScroll() {
        super.computeScroll()
        if (scroller.computeScrollOffset()) {
            scrollTo(scroller.currX, scroller.currY)
            postInvalidateOnAnimation(left, top, right, bottom)
        }
    }

    override fun onNestedPreFling(target: View?, velocityX: Float, velocityY: Float): Boolean {
        return super.onNestedPreFling(target, velocityX, velocityY)
    }

    override fun onNestedFling(
        target: View?,
        velocityX: Float,
        velocityY: Float,
        consumed: Boolean
    ): Boolean {
        scroller.fling(
            scrollX,
            scrollY,
            velocityX.toInt(),
            velocityY.toInt(),
            0,
            0,
            -height + 500,
            0,
            0,
            500
        )
        postInvalidateOnAnimation(left, top, right, bottom)
        return true
    }
}